package com.security.demo.handel;

import com.google.gson.Gson;
import com.security.demo.vo.R;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 *  自定义的security的认证成功处理器
 */

@Component("customAuthenticationSuccessHandler")
public class CustomAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
            throws IOException, ServletException {
        R result = R.ok().setMessage("登录成功。");
        response.setContentType("application/json;charset=UTF-8");
        // 校验验证码
        String code = (String) request.getSession().getAttribute("code");
        String codeInput = request.getParameter("codeInput");
        if(code==null || codeInput==null) {
            result.setCode(501).setMessage("验证码为空");
        }else {
            if (!code.equalsIgnoreCase(codeInput)) {
                result.setCode(501).setMessage("验证码错误");
            }
        }
        Gson gson = new Gson();
        response.getWriter().write(gson.toJson(result));
    }
}